package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    //开始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    //序列号的个位数
    public static final int COUNT_BITS = 32;

    private final StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        //1.生成时间戳一共是32位
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);//toEpochSecond方法是将时间转换为秒数表示UTC时区
        long timestap = nowSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        //获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        //自增长 刚好可以根据：统计访问量 返回的是自增长的值是bit类型的位数是32位
        Long count = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);

        return timestap << COUNT_BITS | count; //将时间戳左移32位，然后与序列号进行或运算比如
    }

}
